package com.jlh.viewer.sychronize;

import java.util.concurrent.TimeUnit;

/**
 * @author mymx.jlh
 * @version 1.0.0 2018/4/21 9:15
 */
public class ManySync {

    public static void main(String[] args) throws InterruptedException {
        Resources resources = new Resources();

        Thread thread1 = new Thread(() -> {
            try {
                synchronized (resources.resource1) {
                    System.out.println("thread1: resource1 get, and then get resource 2");
                    TimeUnit.SECONDS.sleep(0);
                    synchronized (resources.resource2) {
                        System.out.println("thread1: getAll");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
//        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            try {
                synchronized (resources.resource2) {
                    System.out.println("thread2: resource2 get, and then get resource 1");
                    TimeUnit.SECONDS.sleep(1);
                    synchronized (resources.resource1) {
                        System.out.println("thread2: getAll");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();


        TimeUnit.SECONDS.sleep(2);
        System.out.println("start interrupt");
        thread1.interrupt();

    }

    private static class Resources {
        public String resource1 = "1";
        public String resource2 = "2";

    }
}
